﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BLL;
using Common;
using ServiceCenterApp.Helper;
using Model;
using DevExpress.Utils;
using DevExpress.XtraEditors;

namespace ServiceCenterApp
{
    public partial class FormCateogory : XtraForm, IChildForm
    {
        CategoryBLL bll = new CategoryBLL();
        OperationMode operationMode = OperationMode.Insert;
        Category currentCategory = null;
        List<Category> categoryList = new List<Category>();

        public FormCateogory()
        {
            InitializeComponent();
        }

        private void FormCateogory_Load(object sender, EventArgs e)
        {
            loadData();
            WinformHelper.BindLookUpEdit<Category>(lueCategory, categoryList, "Name", "ID");
        }

        private void loadData()
        {
            var nodes = bll.GetCategoryTreeNodes();
            TreeNode root = new TreeNode("所有分类");
            root.Tag = new Category { ID = 0 };
            root.Nodes.AddRange(nodes.ToArray());
            categoryList.Clear();
            categoryList.AddRange(bll.GetAllCategory());
            this.Invoke(new MethodInvoker(() =>
            {
                this.treeView1.Nodes.Clear();
                this.treeView1.Nodes.Add(root);
                this.gridControl1.DataSource = null;
                this.gridControl1.DataSource = categoryList;
            }));
        }

        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            currentCategory = this.gridView1.GetFocusedRow() as Category;
            if (currentCategory != null)
            {
                this.txtName.Text = currentCategory.Name;
                this.operationMode = OperationMode.Update;
                var node = WinformHelper.SearchNode(this.treeView1.Nodes, currentCategory.ParentID);
                if (node != null)
                {
                    this.treeView1.SelectedNode = node;
                    node.Expand();
                }
                Program.MainWindow.ShowMessage("已进入修改模式，修改名称和父分类后点击保存按钮！");
            }
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {

        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            this.operationMode = OperationMode.Insert;
            this.currentCategory = null;
            this.txtName.Text = "";
            this.txtName.Focus();
            //this.treeView1.SelectedNode = this.treeView1.Nodes[0];
            Program.MainWindow.ShowMessage("已进入新增模式，请输入名称选择父分类后点击保存按钮新增分类！");
        }

        public void Save()
        {
            if (string.IsNullOrEmpty(this.txtName.Text))
            {
                WinformHelper.ShowError("请输入名称！");
                return;
            }
            else if (this.txtName.Text.Length > 512)
            {
                WinformHelper.ShowError("名称长度不能超过512！");
                return;
            }
            if (this.treeView1.SelectedNode == null)
            {
                WinformHelper.ShowError("请选择父类！");
                return;
            }

            TreeNode node = null;

            try
            {
                switch (operationMode)
                {
                    case OperationMode.Insert:
                        currentCategory = new Category { Name = this.txtName.Text };
                        currentCategory.ParentID = ((Category)this.treeView1.SelectedNode.Tag).ID;
                        bll.Insert(currentCategory);
                        node = new TreeNode(currentCategory.Name);
                        node.Tag = currentCategory;
                        operationMode = OperationMode.Update;
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.treeView1.SelectedNode.Nodes.Add(node);
                            this.treeView1.Update();
                            this.gridView1.BeginDataUpdate();
                            categoryList.Add(currentCategory);
                            this.gridView1.EndDataUpdate();
                            Program.MainWindow.ShowMessage("添加分类成功！");
                            this.gridView1.FocusedRowHandle = this.gridView1.GetRowHandle(categoryList.Count - 1);
                        }));
                        break;
                    case OperationMode.Update:
                        currentCategory.Name = this.txtName.Text;
                        currentCategory.ParentID = ((Category)this.treeView1.SelectedNode.Tag).ID;
                        bll.Update(currentCategory);
                        this.Invoke(new MethodInvoker(() =>
                        {
                            this.gridView1.BeginDataUpdate();
                            this.gridView1.EndDataUpdate();
                            this.treeView1.Update();
                            node = WinformHelper.SearchNode(this.treeView1.Nodes, currentCategory.ID);
                            if (node != null)
                            {
                                node.Parent.Nodes.Remove(node);
                            }
                            node = new TreeNode(currentCategory.Name);
                            node.Tag = currentCategory;
                            this.treeView1.SelectedNode.Nodes.Add(node);
                            this.treeView1.Update();
                            Program.MainWindow.ShowMessage("修改分类成功！");
                        }));
                        break;
                }
            }
            catch (Exception ex)
            {
                Program.ShowError(ex);
            }
        }

        public void Delete()
        {
            this.currentCategory = this.gridView1.GetFocusedRow() as Category;
            if (this.currentCategory == null)
            {
                WinformHelper.ShowInformation("请在上方表格中选择要删除的分类！");
                return;
            }

            var children = categoryList.Where(x => x.ParentID == currentCategory.ID).ToList();
            if (children.Count > 0)
            {
                if (XtraMessageBox.Show("您删除的分类下还有子分类，删除此分类后此分类所有的子分类都将归类为所有分类，确定要删除吗？", "警告", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No)
                {
                    return;
                }
            }

            try
            {
                bll.Delete(currentCategory);
                this.Invoke(new MethodInvoker(() =>
                {
                    var category = categoryList.Where(x => x.ID == currentCategory.ID).FirstOrDefault();
                    if (category != null)
                    {
                        this.gridView1.BeginDataUpdate();
                        categoryList.Remove(category);
                        this.gridView1.EndDataUpdate();
                        var node = WinformHelper.SearchNode(this.treeView1.Nodes, category.ID);
                        if (node != null)
                        {
                            node.Parent.Nodes.Remove(node);
                            this.treeView1.Update();
                        }
                    }
                    Program.MainWindow.ShowMessage("删除分类成功");
                }));
                gridView1_FocusedRowChanged(null, null);
            }
            catch (Exception ex)
            {
                Program.ShowError(ex);
            }
        }

        public void RefreshData()
        {
            loadData();
        }
    }
}
